package com.dries.portal.module.coupon.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dries.portal.module.coupon.enums.CouponStatus;
import com.dries.common.exception.ApiException;
import com.dries.portal.module.coupon.entity.Coupon;
import com.dries.portal.module.coupon.service.ICouponService;
import com.dries.portal.module.coupon.service.IRabbitMqServices;
import com.dries.portal.module.coupon.vo.CouponRabbitMqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: rabbitmq 相关服务接口实现
 * 将Cache 中的Coupon 的状态变化同步到DB中
 * @Author ZSY
 * @createTime 2020/8/3 18:00
 */
@Slf4j
@Service
public class CouponRabbitMqServiceImpl implements IRabbitMqServices {

    @Resource
    private ICouponService couponService;

    /**
     * 提现成功消息
     *
     * @param message
     */
    @Override
    public void consumeCashDrawsRabbitMqMsg(String message) {

    }

    /**
     * 消费优惠券消息
     */
    @Override
    public void consumeCouponRabbitMqMsg(String message) {
        if (StrUtil.isNotEmpty(message)) {
            CouponRabbitMqMessage couponInfo = JSONUtil.toBean(message, CouponRabbitMqMessage.class);
            log.info("发送消息内容：{}", message.toString());
            CouponStatus status = CouponStatus.of(couponInfo.getStatus());
            switch (status) {
                case USABLE:
                    break;
                case USED:
                    processUsedCoupons(couponInfo, status);
                    break;
                case EXPIRED:
                    processExpiredCoupons(couponInfo, status);
                    break;
            }
        }
    }

    /**
     * 处理已使用的用户优惠券
     */
    private void processUsedCoupons(CouponRabbitMqMessage message, CouponStatus status) {
        // TODO 给用户发送短信
        processCouponByStatus(message, status);
    }

    /**
     * 处理过期的优惠券
     */
    private void processExpiredCoupons(CouponRabbitMqMessage message, CouponStatus status) {
        // TODO 给用户发送推送
        processCouponByStatus(message, status);
    }

    /**
     * 根据状态处理优惠券信息
     */
    private void processCouponByStatus(CouponRabbitMqMessage message, CouponStatus status) {
        List<Coupon> coupons = couponService.listByIds(message.getIds());
        if (CollectionUtils.isEmpty(coupons) || coupons.size() != message.getIds().size()) {
            throw new ApiException("没有查询到优惠券信息");
        }
        coupons.forEach(e -> e.setStatus(status));
        couponService.saveOrUpdateBatch(coupons);
        log.info("修改的优惠券数: {}", coupons.size());
    }
}
